﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    public class ConverUtility
    {

        /// <summary>
        /// 将IList<ArraySegment<byte>> list 转成byte[]
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static byte[] ConvertToByteArray(IList<ArraySegment<byte>> list)
        {
            var bytes = new byte[list.Sum(asb => asb.Count)];
            int pos = 0;

            foreach (var asb in list)
            {
                Buffer.BlockCopy(asb.Array, asb.Offset, bytes, pos, asb.Count);
                pos += asb.Count;
            }

            return bytes;
        }

        
        /// <summary>
        /// 将字符串转成十六进制的Hex
        /// </summary>
        /// <returns></returns>
        public static string ConvertToHexString(string data)
        {
            byte[] bytes = Encoding.Default.GetBytes(data);
            //有十进制值的字符串 decString 转换为具有十六进制值的字符串 hexString。
            string hexString = BitConverter.ToString(bytes);
            hexString = hexString.Replace("-", "");

            return hexString;
        }
        /// <summary>
        /// 将hex字符串转int
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static int ConvertToInt(string data = "0x00001D37")
        {
            return Convert.ToInt32(data, 16);
        }
        //string aa = "0x00001D37";
        // Console.WriteLine(Convert.ToInt32(aa,16));

        public static byte[] StringToBytes(string data)
        {
            byte[] bytes = Encoding.Default.GetBytes(data);
            return bytes;
        }

        public static string ToBytesString(byte[] data)
        {
            return  System.Text.Encoding.UTF8.GetString(data);
        }

        public static string ByteToHexString(byte[] bytes)
        {
           return   BitConverter.ToString(bytes, 0);
        }
        //无符号整数转换为其等效的字符串表示形式
        public static string ToBinary(int x)
        {
            char[] buff = new char[32];

            for (int i = 31; i >= 0; i--)
            {
                int mask = 1 << i;
                buff[31 - i] = (x & mask) != 0 ? '1' : '0';
            }

            return new string(buff);
        }

    }

    
}
